package cn.com.haopy.yue.ai.wx.service;


import cn.com.haopy.yue.ai.core.config.ChatApiProperties;
import cn.com.haopy.yue.ai.core.utils.HttpUtils;
import cn.com.haopy.yue.ai.wx.constant.ConsChat;
import cn.com.haopy.yue.ai.wx.dto.AIChartMsgDto;
import cn.com.haopy.yue.ai.wx.dto.AIChartMsgResponseDto;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * Ai聊听会话接口
 */
@Service
@Slf4j
public class ChatAiApiService {

    @Autowired
    private ChatApiProperties chatProperties;


    private static Map<String, Object> toMap(Object entity) {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = entity.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true); // 使得私有字段也可以访问
            try {
                map.put(field.getName(), field.get(entity));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

    public Map<String, String> handHeader(String key) {
        //头部签名
        Map<String, String> header = new HashMap<>();
        System.out.println("头：" + key);
        header.put("Authorization", key);
        return header;
    }


    public AIChartMsgResponseDto chatMessage(String userId, String conversationId, Object input, Object query, String key) throws Exception {
        AIChartMsgDto msgDto = new AIChartMsgDto();
        msgDto.setConversation_id(conversationId);
        msgDto.setInputs(input);
        msgDto.setQuery(query);
        msgDto.setUser(userId);
        Map<String, Object> params = toMap(msgDto);
        JSONObject data = HttpUtils.postJSON(chatProperties.getRootUrl() + ConsChat.chat_message, handHeader(key), params);
        return handleResult(data);
    }


    @SuppressWarnings({"rawtypes", "unchecked"})
    private static AIChartMsgResponseDto handleResult(JSONObject data) throws Exception {
        System.out.println("chatAi ret:" + data);
        if (data == null) {
            throw new Exception("chatAi 返回数据错误");
        }
        AIChartMsgResponseDto chartMsgResDto = data.toJavaObject(AIChartMsgResponseDto.class);

        System.out.println(chartMsgResDto);
        return chartMsgResDto;
    }
}
